<?php

namespace App\Services;

use App\Models\Post;
use App\Models\Category;
use App\Models\Tag;
use App\Models\User;
use Illuminate\Support\Str;

/**
 * 搜索服务类
 * 
 * 职责：
 * - 处理搜索相关的业务逻辑
 * - 前台搜索（只搜索已发布内容）
 * - 后台全局搜索（搜索所有内容）
 * - 搜索结果格式化
 */
class SearchService extends BaseService
{
    /**
     * 前台搜索（只搜索已发布的内容）
     * 
     * @param string $query 搜索关键词
     * @return array 包含 posts, categories, tags, users 的数组
     */
    public function search(string $query): array
    {
        if (empty(trim($query))) {
            return [
                'posts' => [],
                'categories' => [],
                'tags' => [],
                'users' => []
            ];
        }

        return [
            'posts' => $this->searchPublishedPosts($query),
            'categories' => $this->searchCategories($query),
            'tags' => $this->searchTags($query),
            'users' => $this->searchUsers($query)
        ];
    }

    /**
     * 后台全局搜索（搜索所有内容）
     * 
     * @param string $query 搜索关键词
     * @return array 按类型分组的结果，自动过滤空结果
     */
    public function globalSearch(string $query): array
    {
        if (empty(trim($query))) {
            return [];
        }

        $results = [
            'post' => $this->searchAllPosts($query),
            'category' => $this->searchAllCategories($query),
            'tag' => $this->searchAllTags($query),
            'user' => $this->searchAllUsers($query)
        ];

        // 移除空结果
        return array_filter($results, fn($group) => $group->isNotEmpty());
    }

    /**
     * 搜索已发布的文章（前台用）
     * 
     * @param string $query 搜索关键词
     * @param int $limit 返回数量
     * @return \Illuminate\Support\Collection
     */
    protected function searchPublishedPosts(string $query, int $limit = 5)
    {
        return Post::with(['category', 'tags', 'author'])
            ->published()
            ->where(function($q) use ($query) {
                $q->where('title', 'like', '%' . $query . '%')
                  ->orWhere('content', 'like', '%' . $query . '%');
            })
            ->latestPublished()
            ->limit($limit)
            ->get()
            ->map(function ($post) {
                return [
                    'id' => $post->id,
                    'type' => 'post',
                    'title' => $post->title,
                    'excerpt' => Str::limit(strip_tags($post->content), 100),
                    'url' => route('blog.posts.show', $post->slug),
                    'slug' => $post->slug,
                    'category' => $post->category ? [
                        'name' => $post->category->name,
                        'url' => route('blog.categories.show', $post->category->slug)
                    ] : null,
                    'author' => [
                        'name' => $post->author->name,
                        'avatar' => $post->author->profile_photo_url
                    ],
                    'published_at' => $post->published_at->format('Y-m-d')
                ];
            });
    }

    /**
     * 搜索所有文章（后台用）
     * 
     * @param string $query 搜索关键词
     * @param int $limit 返回数量
     * @return \Illuminate\Support\Collection
     */
    protected function searchAllPosts(string $query, int $limit = 5)
    {
        return Post::where('title', 'like', "%{$query}%")
            ->orWhere('content', 'like', "%{$query}%")
            ->take($limit)
            ->get()
            ->map(function ($post) {
                return [
                    'id' => $post->id,
                    'title' => $post->title,
                    'description' => Str::limit($post->excerpt, 100),
                    'url' => route('admin.posts.edit', $post)
                ];
            });
    }

    /**
     * 搜索分类（前台用）
     * 
     * @param string $query 搜索关键词
     * @param int $limit 返回数量
     * @return \Illuminate\Support\Collection
     */
    protected function searchCategories(string $query, int $limit = 3)
    {
        return Category::where('name', 'like', '%' . $query . '%')
            ->limit($limit)
            ->get()
            ->map(function ($category) {
                return [
                    'id' => $category->id,
                    'type' => 'category',
                    'name' => $category->name,
                    'url' => route('blog.categories.show', $category->slug),
                    'slug' => $category->slug,
                    'description' => $category->description
                ];
            });
    }

    /**
     * 搜索所有分类（后台用）
     * 
     * @param string $query 搜索关键词
     * @param int $limit 返回数量
     * @return \Illuminate\Support\Collection
     */
    protected function searchAllCategories(string $query, int $limit = 3)
    {
        return Category::where('name', 'like', "%{$query}%")
            ->take($limit)
            ->get()
            ->map(function ($category) {
                return [
                    'id' => $category->id,
                    'title' => $category->name,
                    'url' => route('admin.categories.edit', $category)
                ];
            });
    }

    /**
     * 搜索标签（前台用）
     * 
     * @param string $query 搜索关键词
     * @param int $limit 返回数量
     * @return \Illuminate\Support\Collection
     */
    protected function searchTags(string $query, int $limit = 3)
    {
        return Tag::where('name', 'like', '%' . $query . '%')
            ->limit($limit)
            ->get()
            ->map(function ($tag) {
                return [
                    'id' => $tag->id,
                    'type' => 'tag',
                    'name' => $tag->name,
                    'url' => route('blog.tags.show', $tag->slug)
                ];
            });
    }

    /**
     * 搜索所有标签（后台用）
     * 
     * @param string $query 搜索关键词
     * @param int $limit 返回数量
     * @return \Illuminate\Support\Collection
     */
    protected function searchAllTags(string $query, int $limit = 3)
    {
        return Tag::where('name', 'like', "%{$query}%")
            ->take($limit)
            ->get()
            ->map(function ($tag) {
                return [
                    'id' => $tag->id,
                    'title' => $tag->name,
                    'url' => route('admin.tags.edit', $tag)
                ];
            });
    }

    /**
     * 搜索用户（前台用）
     * 
     * @param string $query 搜索关键词
     * @param int $limit 返回数量
     * @return \Illuminate\Support\Collection
     */
    protected function searchUsers(string $query, int $limit = 3)
    {
        return User::where('name', 'like', '%' . $query . '%')
            ->limit($limit)
            ->get()
            ->map(function ($user) {
                return [
                    'id' => $user->id,
                    'type' => 'user',
                    'name' => $user->name,
                    'avatar' => $user->profile_photo_url
                ];
            });
    }

    /**
     * 搜索所有用户（后台用）
     * 
     * @param string $query 搜索关键词
     * @param int $limit 返回数量
     * @return \Illuminate\Support\Collection
     */
    protected function searchAllUsers(string $query, int $limit = 3)
    {
        return User::where('name', 'like', "%{$query}%")
            ->orWhere('email', 'like', "%{$query}%")
            ->take($limit)
            ->get()
            ->map(function ($user) {
                return [
                    'id' => $user->id,
                    'title' => $user->name,
                    'description' => $user->email,
                    'url' => route('admin.users.edit', $user)
                ];
            });
    }
}

